"use client"

import { useState } from "react"
import {
    View,
    Text,
    StyleSheet,
    TouchableOpacity,
    Modal,
    Platform,
    ScrollView,
    TextInput,
    Alert,
    Image,
} from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { LinearGradient } from "expo-linear-gradient"
import { ChevronLeft, X, Check, Star, Zap, Gift, Clock, BookOpen, Sparkles } from "lucide-react-native"
import { theme } from "@/constants/theme"
import { useRouter } from "expo-router"
import Animated, { FadeInDown } from "react-native-reanimated"

interface SubscriptionPlan {
    id: string
    duration: string
    price: number
    originalPrice: number
    popular?: boolean
    features: string[]
}

export default function VipSubscriptionScreen() {
    const router = useRouter()
    const [activationModalVisible, setActivationModalVisible] = useState(false)
    const [activationCode, setActivationCode] = useState("")
    const [error, setError] = useState("")
    const [selectedPlan, setSelectedPlan] = useState<string | null>("year3") // 默认选中3年套餐

    const plans: SubscriptionPlan[] = [
        {
            id: "year1",
            duration: "1年",
            price: 398,
            originalPrice: 398,
            features: ["全部单词书", "专属学习计划", "无广告体验"],
        },
        {
            id: "year3",
            duration: "3年",
            price: 539,
            originalPrice: 798,
            popular: true,
            features: ["全部单词书", "专属学习计划", "无广告体验", "优先客服支持"],
        },
        {
            id: "year12",
            duration: "12年",
            price: 666,
            originalPrice: 1999,
            features: ["全部单词书", "专属学习计划", "无广告体验", "优先客服支持", "终身更新"],
        },
    ]

    const handleActivate = (planId: string) => {
        setSelectedPlan(planId)
        setActivationModalVisible(true)
    }

    const handleSubmitCode = () => {
        if (!activationCode.trim()) {
            setError("请输入激活码")
            return
        }

        // 模拟激活成功
        Alert.alert("激活成功", "您已成功开通VIP会员", [
            {
                text: "确定",
                onPress: () => {
                    router.back()
                },
            },
        ])
    }

    const handleClose = () => {
        setActivationModalVisible(false)
        setActivationCode("")
        setError("")
    }

    // 获取当前选中的套餐
    const selectedPlanData = plans.find((plan) => plan.id === selectedPlan) || plans[1]

    return (
        <SafeAreaView style={styles.container} edges={["top"]}>
            <LinearGradient
                colors={theme.colors.neutral.backgroundGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}
                style={styles.gradientBackground}
            >
                {/* 头部 */}
                <View style={styles.header}>
                    <TouchableOpacity style={styles.backButton} onPress={() => router.back()}>
                        <ChevronLeft size={24} color={theme.colors.neutral.black} />
                    </TouchableOpacity>
                    <Text style={styles.headerTitle}>会员中心</Text>
                    <View style={styles.headerRight} />
                </View>

                <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
                    {/* 顶部卡片 */}
                    <Animated.View entering={FadeInDown.delay(100).springify()}>
                        <LinearGradient
                            colors={["#6A4AD4", "#8A6CEA"]}
                            start={{ x: 0, y: 0 }}
                            end={{ x: 1, y: 0 }}
                            style={styles.topCard}
                        >
                            <View style={styles.topCardContent}>
                                <View style={styles.avatarContainer}>
                                    <Image
                                        source={{ uri: "https://cdn-icons-png.flaticon.com/512/3135/3135715.png" }}
                                        style={styles.avatar}
                                    />
                                    <View style={styles.crownBadge}>
                                        <Star size={12} color="#FFF" fill="#FFF" />
                                    </View>
                                </View>
                                <View style={styles.userInfoContainer}>
                                    <Text style={styles.userStatus}>您当前非会员</Text>
                                    <Text style={styles.trialText}>试用时间剩余: 36小时</Text>
                                </View>
                            </View>
                        </LinearGradient>
                    </Animated.View>

                    {/* 会员权益 */}
                    <Animated.View entering={FadeInDown.delay(200).springify()}>
                        <View style={styles.benefitsSection}>
                            <Text style={styles.sectionTitle}>会员特权</Text>

                            <View style={styles.benefitsGrid}>
                                <View style={styles.benefitItem}>
                                    <View style={[styles.benefitIcon, { backgroundColor: theme.colors.secondary.green.light }]}>
                                        <BookOpen size={20} color={theme.colors.secondary.green.default} />
                                    </View>
                                    <Text style={styles.benefitText}>全部单词书</Text>
                                </View>

                                <View style={styles.benefitItem}>
                                    <View style={[styles.benefitIcon, { backgroundColor: theme.colors.secondary.orange.light }]}>
                                        <Zap size={20} color={theme.colors.secondary.orange.default} />
                                    </View>
                                    <Text style={styles.benefitText}>专属学习计划</Text>
                                </View>

                                <View style={styles.benefitItem}>
                                    <View style={[styles.benefitIcon, { backgroundColor: theme.colors.primary.purpleLight }]}>
                                        <Gift size={20} color={theme.colors.primary.purple} />
                                    </View>
                                    <Text style={styles.benefitText}>无广告体验</Text>
                                </View>

                                <View style={styles.benefitItem}>
                                    <View style={[styles.benefitIcon, { backgroundColor: "#E3F2FD" }]}>
                                        <Clock size={20} color={theme.colors.primary.default} />
                                    </View>
                                    <Text style={styles.benefitText}>终身更新</Text>
                                </View>
                            </View>
                        </View>
                    </Animated.View>

                    {/* 会员套餐 */}
                    <Animated.View entering={FadeInDown.delay(300).springify()}>
                        <View style={styles.plansSection}>
                            <Text style={styles.sectionTitle}>会员套餐</Text>

                            <View style={styles.plansContainer}>
                                {plans.map((plan) => (
                                    <TouchableOpacity
                                        key={plan.id}
                                        style={[
                                            styles.planCard,
                                            selectedPlan === plan.id && styles.selectedPlanCard,
                                            plan.popular && styles.popularPlanCard,
                                        ]}
                                        onPress={() => setSelectedPlan(plan.id)}
                                    >
                                        {plan.popular && (
                                            <View style={styles.popularBadge}>
                                                <Text style={styles.popularBadgeText}>推荐</Text>
                                            </View>
                                        )}

                                        <Text style={[styles.durationText, selectedPlan === plan.id && styles.selectedDurationText]}>
                                            {plan.duration}
                                        </Text>

                                        <View style={styles.priceContainer}>
                                            <Text style={[styles.currencySymbol, selectedPlan === plan.id && styles.selectedCurrencySymbol]}>
                                                ¥
                                            </Text>
                                            <Text style={[styles.priceText, selectedPlan === plan.id && styles.selectedPriceText]}>
                                                {plan.price}
                                            </Text>
                                        </View>

                                        <Text style={styles.originalPriceText}>原价: ¥{plan.originalPrice}</Text>

                                        {selectedPlan === plan.id && (
                                            <View style={styles.checkmarkContainer}>
                                                <Check size={16} color="#FFF" />
                                            </View>
                                        )}
                                    </TouchableOpacity>
                                ))}
                            </View>

                            {/* 选中套餐的详细信息 */}
                            <View style={styles.selectedPlanDetails}>
                                <Text style={styles.selectedPlanTitle}>
                                    <Text style={{ color: theme.colors.primary.default }}>{selectedPlanData.duration}</Text> 会员包含:
                                </Text>

                                {selectedPlanData.features.map((feature, index) => (
                                    <View key={index} style={styles.featureItem}>
                                        <View style={styles.featureCheckmark}>
                                            <Check size={12} color={theme.colors.secondary.green.default} />
                                        </View>
                                        <Text style={styles.featureText}>{feature}</Text>
                                    </View>
                                ))}
                            </View>

                            {/* 激活按钮 */}
                            <TouchableOpacity style={styles.activateButton} onPress={() => handleActivate(selectedPlan)}>
                                <LinearGradient
                                    colors={theme.colors.primary.gradient}
                                    start={{ x: 0, y: 0 }}
                                    end={{ x: 1, y: 0 }}
                                    style={styles.activateButtonGradient}
                                >
                                    <Sparkles size={18} color="#FFF" style={{ marginRight: 8 }} />
                                    <Text style={styles.activateButtonText}>立即开通</Text>
                                </LinearGradient>
                            </TouchableOpacity>

                            <TouchableOpacity style={styles.restorePurchaseButton}>
                                <Text style={styles.restorePurchaseText}>恢复购买</Text>
                            </TouchableOpacity>
                        </View>
                    </Animated.View>

                    {/* 底部说明 */}
                    <Animated.View entering={FadeInDown.delay(400).springify()} style={styles.footerSection}>
                        <Text style={styles.footerText}>
                            会员在有效期内，获取APP的完全访问权，使用提供的所有单词书、享受升级送代服务，不另收取费用。
                        </Text>

                        <TouchableOpacity style={styles.agreementButton}>
                            <Text style={styles.agreementText}>《会员服务协议》</Text>
                        </TouchableOpacity>

                        <Image
                            source={{ uri: "https://cdn-icons-png.flaticon.com/512/3135/3135789.png" }}
                            style={styles.footerImage}
                        />
                    </Animated.View>
                </ScrollView>

                {/* 激活码弹窗 */}
                <Modal animationType="fade" transparent={true} visible={activationModalVisible} onRequestClose={handleClose}>
                    <View style={styles.modalOverlay}>
                        <Animated.View style={styles.modalContent} entering={FadeInDown.springify()}>
                            <LinearGradient colors={["#F8F9FF", "#F0F5FF"]} style={styles.modalGradient}>
                                <View style={styles.modalHeader}>
                                    <Text style={styles.modalTitle}>输入VIP激活码</Text>
                                    <TouchableOpacity onPress={handleClose} style={styles.closeButton}>
                                        <X size={20} color={theme.colors.neutral.darkGray} />
                                    </TouchableOpacity>
                                </View>

                                <View style={styles.modalImageContainer}>
                                    <Image
                                        source={{ uri: "https://cdn-icons-png.flaticon.com/512/3135/3135715.png" }}
                                        style={styles.modalImage}
                                    />
                                    <View style={styles.modalCrownBadge}>
                                        <Star size={16} color="#FFF" fill="#FFF" />
                                    </View>
                                </View>

                                <Text style={styles.modalDescription}>请输入您的VIP激活码以解锁所有高级功能</Text>

                                <View style={styles.inputContainer}>
                                    <TextInput
                                        style={[styles.input, error ? styles.inputError : null]}
                                        placeholder="请输入激活码"
                                        value={activationCode}
                                        onChangeText={(text) => {
                                            setActivationCode(text)
                                            if (error) setError("")
                                        }}
                                        autoCapitalize="characters"
                                        autoCorrect={false}
                                        placeholderTextColor="#AAAAAA"
                                    />
                                    {error ? <Text style={styles.errorText}>{error}</Text> : null}
                                </View>

                                <TouchableOpacity style={styles.submitButton} onPress={handleSubmitCode}>
                                    <LinearGradient
                                        colors={theme.colors.primary.gradient}
                                        start={{ x: 0, y: 0 }}
                                        end={{ x: 1, y: 0 }}
                                        style={styles.submitButtonGradient}
                                    >
                                        <Text style={styles.submitButtonText}>激活会员</Text>
                                    </LinearGradient>
                                </TouchableOpacity>
                            </LinearGradient>
                        </Animated.View>
                    </View>
                </Modal>
            </LinearGradient>
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.colors.neutral.background,
    },
    gradientBackground: {
        flex: 1,
    },
    header: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.md,
    },
    backButton: {
        width: 40,
        height: 40,
        borderRadius: 20,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "rgba(255, 255, 255, 0.5)",
    },
    headerTitle: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.black,
    },
    headerRight: {
        width: 40,
    },
    scrollView: {
        flex: 1,
    },
    // 顶部卡片样式
    topCard: {
        marginHorizontal: theme.spacing.lg,
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.lg,
        marginBottom: theme.spacing.lg,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(106, 74, 212, 0.5)",
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.3,
                shadowRadius: 8,
            },
            android: {
                elevation: 6,
            },
        }),
    },
    topCardContent: {
        flexDirection: "row",
        alignItems: "center",
    },
    avatarContainer: {
        position: "relative",
        marginRight: theme.spacing.lg,
    },
    avatar: {
        width: 60,
        height: 60,
        borderRadius: 30,
        borderWidth: 2,
        borderColor: "rgba(255, 255, 255, 0.3)",
    },
    crownBadge: {
        position: "absolute",
        bottom: -5,
        right: -5,
        width: 24,
        height: 24,
        borderRadius: 12,
        backgroundColor: theme.colors.secondary.orange.default,
        alignItems: "center",
        justifyContent: "center",
        borderWidth: 2,
        borderColor: "#FFF",
    },
    userInfoContainer: {
        flex: 1,
    },
    userStatus: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.bold,
        color: "#FFF",
        marginBottom: 4,
    },
    trialText: {
        fontSize: theme.fontSize.sm,
        color: "rgba(255, 255, 255, 0.8)",
    },
    // 会员权益部分
    benefitsSection: {
        marginHorizontal: theme.spacing.lg,
        marginBottom: theme.spacing.lg,
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.lg,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.2,
                shadowRadius: 4,
            },
            android: {
                elevation: 3,
            },
        }),
    },
    sectionTitle: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.black,
        marginBottom: theme.spacing.md,
        paddingLeft: theme.spacing.xs,
        borderLeftWidth: 4,
        borderLeftColor: theme.colors.primary.default,
    },
    benefitsGrid: {
        flexDirection: "row",
        flexWrap: "wrap",
        justifyContent: "space-between",
    },
    benefitItem: {
        width: "48%",
        flexDirection: "row",
        alignItems: "center",
        marginBottom: theme.spacing.md,
    },
    benefitIcon: {
        width: 40,
        height: 40,
        borderRadius: 20,
        alignItems: "center",
        justifyContent: "center",
        marginRight: theme.spacing.sm,
    },
    benefitText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
        fontWeight: theme.fontWeight.medium,
    },
    // 会员套餐部分
    plansSection: {
        marginHorizontal: theme.spacing.lg,
        marginBottom: theme.spacing.lg,
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.lg,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.2,
                shadowRadius: 4,
            },
            android: {
                elevation: 3,
            },
        }),
    },
    plansContainer: {
        flexDirection: "row",
        justifyContent: "space-between",
        marginBottom: theme.spacing.lg,
    },
    planCard: {
        width: "31%",
        borderWidth: 2,
        borderColor: theme.colors.neutral.lightGray,
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.md,
        alignItems: "center",
        position: "relative",
        backgroundColor: "#FFFFFF",
    },
    selectedPlanCard: {
        borderColor: theme.colors.primary.default,
        backgroundColor: "rgba(91, 142, 244, 0.05)",
    },
    popularPlanCard: {
        borderColor: theme.colors.secondary.orange.default,
    },
    popularBadge: {
        position: "absolute",
        top: -10,
        paddingHorizontal: theme.spacing.sm,
        paddingVertical: 2,
        backgroundColor: theme.colors.secondary.orange.default,
        borderRadius: 10,
    },
    popularBadgeText: {
        color: "#FFF",
        fontSize: 10,
        fontWeight: theme.fontWeight.bold,
    },
    durationText: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
        marginBottom: theme.spacing.sm,
        marginTop: theme.spacing.xs,
    },
    selectedDurationText: {
        color: theme.colors.primary.default,
    },
    priceContainer: {
        flexDirection: "row",
        alignItems: "flex-end",
        marginBottom: 4,
    },
    currencySymbol: {
        fontSize: theme.fontSize.sm,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.darkGray,
    },
    selectedCurrencySymbol: {
        color: theme.colors.primary.default,
    },
    priceText: {
        fontSize: theme.fontSize.xl,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.darkGray,
    },
    selectedPriceText: {
        color: theme.colors.primary.default,
    },
    originalPriceText: {
        fontSize: theme.fontSize.xs,
        color: theme.colors.neutral.gray,
        textDecorationLine: "line-through",
        marginBottom: theme.spacing.sm,
    },
    checkmarkContainer: {
        width: 24,
        height: 24,
        borderRadius: 12,
        backgroundColor: theme.colors.primary.default,
        alignItems: "center",
        justifyContent: "center",
        position: "absolute",
        bottom: -10,
    },
    selectedPlanDetails: {
        backgroundColor: "rgba(91, 142, 244, 0.05)",
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.md,
        marginBottom: theme.spacing.lg,
        borderWidth: 1,
        borderColor: "rgba(91, 142, 244, 0.2)",
    },
    selectedPlanTitle: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
        marginBottom: theme.spacing.sm,
    },
    featureItem: {
        flexDirection: "row",
        alignItems: "center",
        marginBottom: 6,
    },
    featureCheckmark: {
        width: 20,
        height: 20,
        borderRadius: 10,
        backgroundColor: "rgba(52, 199, 89, 0.1)",
        alignItems: "center",
        justifyContent: "center",
        marginRight: theme.spacing.sm,
    },
    featureText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.darkGray,
    },
    activateButton: {
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
        marginBottom: theme.spacing.md,
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.default,
                shadowOffset: { width: 0, height: 3 },
                shadowOpacity: 0.3,
                shadowRadius: 5,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    activateButtonGradient: {
        paddingVertical: theme.spacing.md,
        alignItems: "center",
        justifyContent: "center",
        flexDirection: "row",
    },
    activateButtonText: {
        color: "#FFF",
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
    },
    restorePurchaseButton: {
        alignItems: "center",
        paddingVertical: theme.spacing.sm,
    },
    restorePurchaseText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.primary.default,
        textDecorationLine: "underline",
    },
    // 底部说明
    footerSection: {
        marginHorizontal: theme.spacing.lg,
        marginBottom: theme.spacing.xxxl,
        alignItems: "center",
    },
    footerText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.gray,
        textAlign: "center",
        marginBottom: theme.spacing.md,
        lineHeight: 20,
    },
    agreementButton: {
        marginBottom: theme.spacing.xl,
    },
    agreementText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.primary.default,
        textDecorationLine: "underline",
    },
    footerImage: {
        width: 60,
        height: 60,
        opacity: 0.5,
    },
    // 激活码弹窗
    modalOverlay: {
        flex: 1,
        backgroundColor: "rgba(0, 0, 0, 0.5)",
        justifyContent: "center",
        alignItems: "center",
    },
    modalContent: {
        width: "85%",
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: "#000",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.25,
                shadowRadius: 3.84,
            },
            android: {
                elevation: 5,
            },
        }),
    },
    modalGradient: {
        padding: theme.spacing.lg,
        borderRadius: theme.borderRadius.large,
    },
    modalHeader: {
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center",
        marginBottom: theme.spacing.lg,
    },
    modalTitle: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.black,
    },
    closeButton: {
        padding: 4,
    },
    modalImageContainer: {
        alignItems: "center",
        justifyContent: "center",
        marginBottom: theme.spacing.lg,
        position: "relative",
    },
    modalImage: {
        width: 80,
        height: 80,
        borderRadius: 40,
        borderWidth: 3,
        borderColor: theme.colors.primary.light,
    },
    modalCrownBadge: {
        position: "absolute",
        bottom: -5,
        right: "35%",
        width: 30,
        height: 30,
        borderRadius: 15,
        backgroundColor: theme.colors.secondary.orange.default,
        alignItems: "center",
        justifyContent: "center",
        borderWidth: 2,
        borderColor: "#FFF",
    },
    modalDescription: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
        marginBottom: theme.spacing.lg,
        textAlign: "center",
    },
    inputContainer: {
        marginBottom: theme.spacing.lg,
    },
    input: {
        borderWidth: 1,
        borderColor: theme.colors.neutral.lightGray,
        borderRadius: theme.borderRadius.medium,
        paddingHorizontal: theme.spacing.md,
        paddingVertical: theme.spacing.md,
        fontSize: theme.fontSize.md,
        backgroundColor: "#FFF",
    },
    inputError: {
        borderColor: theme.colors.secondary.red.default,
    },
    errorText: {
        color: theme.colors.secondary.red.default,
        fontSize: theme.fontSize.sm,
        marginTop: theme.spacing.xs,
    },
    submitButton: {
        borderRadius: theme.borderRadius.medium,
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.default,
                shadowOffset: { width: 0, height: 3 },
                shadowOpacity: 0.3,
                shadowRadius: 5,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    submitButtonGradient: {
        paddingVertical: theme.spacing.md,
        alignItems: "center",
        justifyContent: "center",
    },
    submitButtonText: {
        color: "#FFF",
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
    },
})

